package com.retry.task.admin.utils;

import java.nio.charset.Charset;
import java.util.Base64;

import javax.xml.bind.DatatypeConverter;

import org.springframework.lang.UsesJava8;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

/**
 * @author gao.gwq
 * @version 1.0
 * @date 2022/6/13  13:42
 * @Description TODO
 */
public abstract class Base64Utils {

    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private static final Base64Delegate delegate;

    static {
        Base64Delegate delegateToUse = null;
        // JDK 8's java.util.Base64 class present?
        if (ClassUtils.isPresent("java.util.Base64", org.springframework.util.Base64Utils.class.getClassLoader())) {
            delegateToUse = new JdkBase64Delegate();
        }
        // Apache Commons Codec present on the classpath?
        else if (ClassUtils.isPresent("org.apache.commons.codec.binary.Base64",
            org.springframework.util.Base64Utils.class.getClassLoader())) {
            delegateToUse = new CommonsCodecBase64Delegate();
        }
        delegate = delegateToUse;
    }

    /**
     * Assert that Byte64 encoding between byte arrays is actually supported.
     *
     * @throws IllegalStateException if neither Java 8 nor Apache Commons Codec is present
     */
    private static void assertDelegateAvailable() {
        Assert.state(delegate != null,
            "Neither Java 8 nor Apache Commons Codec found - Base64 encoding between byte arrays not supported");
    }

    /**
     * Base64-encode the given byte array.
     *
     * @param src the original byte array (may be {@code null})
     * @return the encoded byte array (or {@code null} if the input was {@code null})
     * @throws IllegalStateException if Base64 encoding between byte arrays is not
     * supported, i.e. neither Java 8 nor Apache Commons Codec is present at runtime
     */
    public static byte[] encode(byte[] src) {
        assertDelegateAvailable();
        return delegate.encode(src);
    }

    /**
     * Base64-decode the given byte array.
     *
     * @param src the encoded byte array (may be {@code null})
     * @return the original byte array (or {@code null} if the input was {@code null})
     * @throws IllegalStateException if Base64 encoding between byte arrays is not
     * supported, i.e. neither Java 8 nor Apache Commons Codec is present at runtime
     */
    public static byte[] decode(byte[] src) {
        assertDelegateAvailable();
        return delegate.decode(src);
    }

    /**
     * Base64-encode the given byte array using the RFC 4648
     * "URL and Filename Safe Alphabet".
     *
     * @param src the original byte array (may be {@code null})
     * @return the encoded byte array (or {@code null} if the input was {@code null})
     * @throws IllegalStateException if Base64 encoding between byte arrays is not
     * supported, i.e. neither Java 8 nor Apache Commons Codec is present at runtime
     * @since 4.2.4
     */
    public static byte[] encodeUrlSafe(byte[] src) {
        assertDelegateAvailable();
        return delegate.encodeUrlSafe(src);
    }

    /**
     * Base64-decode the given byte array using the RFC 4648
     * "URL and Filename Safe Alphabet".
     *
     * @param src the encoded byte array (may be {@code null})
     * @return the original byte array (or {@code null} if the input was {@code null})
     * @throws IllegalStateException if Base64 encoding between byte arrays is not
     * supported, i.e. neither Java 8 nor Apache Commons Codec is present at runtime
     * @since 4.2.4
     */
    public static byte[] decodeUrlSafe(byte[] src) {
        assertDelegateAvailable();
        return delegate.decodeUrlSafe(src);
    }

    /**
     * Base64-encode the given byte array to a String.
     *
     * @param src the original byte array (may be {@code null})
     * @return the encoded byte array as a UTF-8 String
     * (or {@code null} if the input was {@code null})
     */
    public static String encodeToString(byte[] src) {
        if (src == null) {
            return null;
        }
        if (src.length == 0) {
            return "";
        }

        if (delegate != null) {
            // Full encoder available
            return new String(delegate.encode(src), DEFAULT_CHARSET);
        } else {
            // JAXB fallback for String case
            return DatatypeConverter.printBase64Binary(src);
        }
    }

    /**
     * Base64-decode the given byte array from an UTF-8 String.
     *
     * @param src the encoded UTF-8 String (may be {@code null})
     * @return the original byte array (or {@code null} if the input was {@code null})
     */
    public static byte[] decodeFromString(String src) {
        if (src == null) {
            return null;
        }
        if (src.isEmpty()) {
            return new byte[0];
        }

        if (delegate != null) {
            // Full encoder available
            return delegate.decode(src.getBytes(DEFAULT_CHARSET));
        } else {
            // JAXB fallback for String case
            return DatatypeConverter.parseBase64Binary(src);
        }
    }

    /**
     * Base64-encode the given byte array to a String using the RFC 4648
     * "URL and Filename Safe Alphabet".
     *
     * @param src the original byte array (may be {@code null})
     * @return the encoded byte array as a UTF-8 String
     * (or {@code null} if the input was {@code null})
     * @throws IllegalStateException if Base64 encoding between byte arrays is not
     * supported, i.e. neither Java 8 nor Apache Commons Codec is present at runtime
     */
    public static String encodeToUrlSafeString(byte[] src) {
        assertDelegateAvailable();
        return new String(delegate.encodeUrlSafe(src), DEFAULT_CHARSET);
    }

    /**
     * Base64-decode the given byte array from an UTF-8 String using the RFC 4648
     * "URL and Filename Safe Alphabet".
     *
     * @param src the encoded UTF-8 String (may be {@code null})
     * @return the original byte array (or {@code null} if the input was {@code null})
     * @throws IllegalStateException if Base64 encoding between byte arrays is not
     * supported, i.e. neither Java 8 nor Apache Commons Codec is present at runtime
     */
    public static byte[] decodeFromUrlSafeString(String src) {
        assertDelegateAvailable();
        return delegate.decodeUrlSafe(src.getBytes(DEFAULT_CHARSET));
    }

    interface Base64Delegate {

        byte[] encode(byte[] src);

        byte[] decode(byte[] src);

        byte[] encodeUrlSafe(byte[] src);

        byte[] decodeUrlSafe(byte[] src);
    }

    @UsesJava8
    static class JdkBase64Delegate implements Base64Delegate {

        @Override
        public byte[] encode(byte[] src) {
            if (src == null || src.length == 0) {
                return src;
            }
            return Base64.getMimeEncoder().encode(src);
        }

        @Override
        public byte[] decode(byte[] src) {
            if (src == null || src.length == 0) {
                return src;
            }
            return Base64.getMimeDecoder().decode(src);
        }

        @Override
        public byte[] encodeUrlSafe(byte[] src) {
            if (src == null || src.length == 0) {
                return src;
            }
            return Base64.getUrlEncoder().encode(src);
        }

        @Override
        public byte[] decodeUrlSafe(byte[] src) {
            if (src == null || src.length == 0) {
                return src;
            }
            return Base64.getUrlDecoder().decode(src);
        }

    }

    static class CommonsCodecBase64Delegate implements Base64Delegate {

        private final org.apache.commons.codec.binary.Base64 base64 =
            new org.apache.commons.codec.binary.Base64();

        private final org.apache.commons.codec.binary.Base64 base64UrlSafe =
            new org.apache.commons.codec.binary.Base64(0, null, true);

        @Override
        public byte[] encode(byte[] src) {
            return this.base64.encode(src);
        }

        @Override
        public byte[] decode(byte[] src) {
            return this.base64.decode(src);
        }

        @Override
        public byte[] encodeUrlSafe(byte[] src) {
            return this.base64UrlSafe.encode(src);
        }

        @Override
        public byte[] decodeUrlSafe(byte[] src) {
            return this.base64UrlSafe.decode(src);
        }

    }
}